package com.itplh.modules.jwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itplh.modules.jwt.annotation.UserLoginToken;
import com.itplh.modules.jwt.pojo.JWTUser;
import com.itplh.modules.jwt.service.JWTUserService;
import com.itplh.modules.jwt.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description:
 * @Author: tanpeng
 * @Date: 2019-07-11 1:09
 * @Version: V1.0
 */
@RestController
@RequestMapping("/jwt")
public class JWTUserController {

    @Autowired
    private JWTUserService userService;

    /**
     * 登录
     * @param user
     * @return
     * @throws JSONException
     */
    @PostMapping("/login")
    public String login(@RequestBody JWTUser user) {
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<JWTUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(JWTUser::getUsername, user.getUsername());
        JWTUser userForBase = userService.getOne(queryWrapper);
        if (userForBase == null) {
            jsonObject.put("message", "登录失败,用户不存在");
            return jsonObject.toString();
        } else {
            if (!userForBase.getPassword().equals(user.getPassword())) {
                jsonObject.put("message", "登录失败,密码错误");
                return jsonObject.toString();
            } else {
                String token = TokenUtil.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject.toString();
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage() {
        return "你已通过验证";
    }
}
